package com.dge.app.slice;

import com.dge.app.ResourceTable;
import com.dge.app.beans.StatisticsBean;
import com.dge.app.common.URLConstants;
import com.dge.app.common.UserInfoMgr;
import com.dge.app.providers.FunctionListProvider;
import com.dge.app.providers.HotSearchProvider;
import com.dge.app.providers.StatisticPanelProvider;
import com.dge.app.utils.GsonUtils;
import com.dge.app.utils.SizeUtils;
import com.dge.app.utils.Utils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.GlideImageLoader;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class MainAbilitySlice extends AbilitySlice {
    public static int STATISTIC_RESULT = 0X02;
    private ArrayList<String> statisticNames = new ArrayList<>();
    static final HiLogLabel label = new HiLogLabel(HiLog.DEBUG, 0x00201, "MainAbilitySlice"); // MY_MODULE=0x00201
    FunctionListProvider funAdapter;
    StatisticPanelProvider statisticAdapter;
    ListContainer functionContainer;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        HiLog.info(label, "onStart");
        initViews();
        initListeners();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }


    private void initViews() {
        ScrollView scrollView = findComponentById(ResourceTable.Id_scrollView);
        scrollView.setHeight(SizeUtils.getScreenHeight());
        scrollView.setWidth(SizeUtils.getScreenWidth());
        initHotSearch();
        initFunctions();
        initBanner();
        initStatistics();
    }

    /**
     * 热搜
     */
    private void initHotSearch() {
        ArrayList<String> array = new ArrayList<>();
        array.add("应用资源");
        array.add("组件资源");
        array.add("数据资源");
        array.add("GIS图层");
        ListContainer listContainer = findComponentById(ResourceTable.Id_rvHotSearch);
        HotSearchProvider hotSearchProvider = new HotSearchProvider(array, this);
        listContainer.setItemProvider(hotSearchProvider);
    }

    /**
     * 统计面板
     */
    private void initStatistics() {
        ListContainer listContainer = findComponentById(ResourceTable.Id_rvStatistic);
        ArrayList<String> data = getStatisticsData();
        listContainer.setLayoutManager(new DirectionalLayoutManager());
        statisticAdapter = new StatisticPanelProvider(data, this);
        statisticAdapter.setStatisticNames(statisticNames);
        // listContainer.setBoundarySwitch(true);  //添加分界线
        listContainer.setItemProvider(statisticAdapter);
        setListContainerHeight(listContainer);
        // listContainer.setBindStateChangedListener(new Component.BindStateChangedListener() {
        //     @Override
        //     public void onComponentBoundToWindow(Component component) {
        //         statisticAdapter.notifyDataChanged();
        //     }
        //
        //     @Override
        //     public void onComponentUnboundFromWindow(Component component) {
        //     }
        // });
        // QuickDragAndSwipe quickDragAndSwipe = new QuickDragAndSwipe()
        //         .setDragMoveFlags(ItemTouchHelper.UP | ItemTouchHelper.DOWN)
        //         .setSwipeMoveFlags(ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);
        // // 拖拽监听
        // OnItemDragListener listener = new OnItemDragListener() {
        //     int startPos = 0;
        //
        //     @Override
        //     public void onItemDragStart(@Nullable RecyclerView.ViewHolder viewHolder, int pos) {
        //         startPos = pos;
        //         VibrateUtils.vibrate(70);
        //     }
        //
        //     @Override
        //     public void onItemDragMoving(@NonNull RecyclerView.ViewHolder source, int from, @NonNull RecyclerView.ViewHolder target, int to) {
        //     }
        //
        //     @Override
        //     public void onItemDragEnd(@NonNull RecyclerView.ViewHolder viewHolder, int pos) {
        //         if (startPos != pos) {
        //             Collections.swap(statisticNames, startPos, pos);
        //             saveStatisticsChange();
        //         }
        //     }
        // };
        // OnItemSwipeListener swipeListener = new OnItemSwipeListener() {
        //     @Override
        //     public void onItemSwipeStart(@Nullable RecyclerView.ViewHolder viewHolder, int bindingAdapterPosition) {
        //     }
        //
        //     @Override
        //     public void onItemSwipeEnd(@NonNull RecyclerView.ViewHolder viewHolder, int bindingAdapterPosition) {
        //     }
        //
        //     @Override
        //     public void onItemSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction, int bindingAdapterPosition) {
        //         statisticNames.remove(bindingAdapterPosition);
        //         saveStatisticsChange();
        //     }
        //
        //     @Override
        //     public void onItemSwipeMoving(@NonNull Canvas canvas, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
        //     }
        // };
        // // 滑动事件
        // quickDragAndSwipe.attachToRecyclerView(binding.rvStatistic)
        //         .setDataCallback(statisticAdapter)
        //         .setItemDragListener(listener)
        //         .setItemSwipeListener(swipeListener);
    }

    /**
     * 功能列表
     */
    private void initFunctions() {
        funAdapter = new FunctionListProvider(getFuncData(), this);
        functionContainer = findComponentById(ResourceTable.Id_rvFunctions);
        TableLayoutManager layoutManager = new TableLayoutManager();// Grid样式
        layoutManager.setRowCount(2);
        functionContainer.setLayoutManager(layoutManager);
        functionContainer.setItemProvider(funAdapter);
        // 拖拽监听
        // QuickDragAndSwipe quickDragAndSwipe = new QuickDragAndSwipe() {
        //     @Override
        //     public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
        //         if (viewHolder.getAdapterPosition() == (funAdapter.getItemCount() - 1)) return 0; //禁用最后一个
        //         int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
        //                 ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
        //         int swipeFlags = 0;
        //         return makeMovementFlags(dragFlags, swipeFlags);
        //     }
        //
        //     @Override
        //     public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
        //         int toPosition = target.getBindingAdapterPosition();
        //         if (toPosition == (funAdapter.getItemCount() - 1)) return false; //最后一个不交换
        //         return super.onMove(recyclerView, viewHolder, target);
        //     }
        // };
        // // 拖拽监听
        // OnItemDragListener listener = new OnItemDragListener() {
        //     int startPos = 0;
        //
        //     @Override
        //     public void onItemDragStart(@Nullable RecyclerView.ViewHolder viewHolder, int pos) {
        //         startPos = pos;
        //         VibrateUtils.vibrate(70);
        //     }
        //
        //     @Override
        //     public void onItemDragMoving(@NonNull RecyclerView.ViewHolder source, int from, @NonNull RecyclerView.ViewHolder target, int to) {
        //     }
        //
        //     @Override
        //     public void onItemDragEnd(@NonNull RecyclerView.ViewHolder viewHolder, int pos) {
        //         if (startPos != pos) {
        //             saveFunctionChange();
        //             View deleteView = ((ViewGroup) viewHolder.itemView).getChildAt(1);
        //             deleteView.setVisibility(View.GONE);
        //             lastVisibleDeleteView = null;
        //         }
        //     }
        // };
        functionContainer.setDraggedListener(Component.DRAG_HORIZONTAL_VERTICAL, new Component.DraggedListener() {

            @Override
            public void onDragDown(Component component, DragInfo dragInfo) {

            }

            @Override
            public void onDragStart(Component component, DragInfo dragInfo) {
                // VibrateUtils.vibrate(70);
            }

            @Override
            public void onDragUpdate(Component component, DragInfo dragInfo) {

            }

            @Override
            public void onDragEnd(Component component, DragInfo dragInfo) {
                int currentIndex = -1;
                for (int i = 0; i < funAdapter.getCount(); i++) {
                    Component item = funAdapter.getComponent(i, null, functionContainer);
                    if (item == component) {
                        currentIndex = i;
                        break;
                    }
                }
                if (Utils.isInComponentArea(component, dragInfo.updatePoint)) {
                    if (funAdapter == null && functionContainer == null && currentIndex != -1) {
                        return;
                    }
                    for (int i = 0; i < funAdapter.getCount(); i++) {
                        Component item = funAdapter.getComponent(i, null, functionContainer);
                        if (Utils.isInComponentArea(item, dragInfo.updatePoint)) {
                            saveFunctionChange();
                            ArrayList<String> list = funAdapter.getItems();
                            Collections.swap(list, currentIndex, i);

                            // View deleteView = ((ViewGroup) viewHolder.itemView).getChildAt(1);
                            // deleteView.setVisibility(View.GONE);
                            // lastVisibleDeleteView = null;
                            funAdapter.notifyDataChanged();
                            break;
                        }
                    }
                }

            }

            @Override
            public void onDragCancel(Component component, DragInfo dragInfo) {

            }
        });
        // // 滑动事件
        // quickDragAndSwipe.attachToRecyclerView(binding.rvFunctions)
        //         .setDataCallback(funAdapter)
        //         .setItemDragListener(listener);
    }

    public void initListeners() {
        Image text = findComponentById(ResourceTable.Id_icMore);
        text.setClickedListener(component -> {
            AbilitySlice abilitySlice = new WebViewAbilitySlice();
            Intent intent = new Intent();
            intent.setParam(WebViewAbilitySlice.EXTRA_URL, URLConstants.URL_USER_BASE + "/overview");
            intent.setParam(WebViewAbilitySlice.EXTRA_TITLE, "概览视窗配置");
            presentForResult(abilitySlice, intent, STATISTIC_RESULT);
        });
        if (functionContainer != null) {
            functionContainer.setItemClickedListener((container, component, position, id) -> {
                String item = (String) functionContainer.getItemProvider().getItem(position);
                if ("更多".equals(item)) {
                    AbilitySlice abilitySlice = new WebViewAbilitySlice();
                    Intent intent = new Intent();
                    intent.setParam(WebViewAbilitySlice.EXTRA_URL, URLConstants.URL_USER_BASE + "/index");
                    intent.setParam(WebViewAbilitySlice.EXTRA_TITLE, "应用库");
                    presentForResult(abilitySlice, intent, STATISTIC_RESULT);
                } else {
                    AbilitySlice abilitySlice = new WebViewAbilitySlice();
                    Intent intent = new Intent();
                    intent.setParam(WebViewAbilitySlice.EXTRA_URL, URLConstants.URL_USER_BASE + "/applet");
                    intent.setParam(WebViewAbilitySlice.EXTRA_TITLE, item);
                    present(abilitySlice, intent);
                }
            });
        }

    }

    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        super.onResult(requestCode, resultIntent);
        if (requestCode == STATISTIC_RESULT) {
            if (resultIntent == null) {
                return;
            }
            HiLog.debug(label, "onActivityResult 概览视窗配置");
            ArrayList<String> items = getStatisticsData();
            statisticAdapter.setStatisticNames(statisticNames);
            statisticAdapter.getItems().clear();
            statisticAdapter.getItems().addAll(items);
        }
    }

    private void saveFunctionChange() {
        UserInfoMgr.functionData = GsonUtils.getGson().toJson(funAdapter.getItems());
        UserInfoMgr.saveUserInfo();
        // if (lastVisibleDeleteView != null && lastVisibleDeleteView.getVisibility() != View.GONE) {
        //     lastVisibleDeleteView.setVisibility(View.GONE);
        //     lastVisibleDeleteView = null;
        // }
    }

    private void saveStatisticsChange() {
        StatisticsBean bean = new StatisticsBean();
        bean.setNames(new ArrayList<>());
        bean.setUrls(new ArrayList<>());
        bean.getNames().addAll(statisticNames);
        bean.getUrls().addAll(statisticAdapter.getItems());
        UserInfoMgr.statisticsData = GsonUtils.getGson().toJson(bean);
        UserInfoMgr.saveUserInfo();
    }

    /**
     * 模拟功能面板数据获取
     */
    private ArrayList<String> getFuncData() {
        String[] functionData = GsonUtils.getGson().fromJson(UserInfoMgr.functionData, String[].class);
        if (functionData == null) {
            return new ArrayList<>();
        }
        if (functionData.length < 10) {
            boolean needAddMore = false;
            if (functionData.length != 0) {
                if (!"更多".equals(functionData[functionData.length - 1])) {
                    needAddMore = true;
                }
            } else {
                needAddMore = true;
            }
            ArrayList<String> list = new ArrayList<>(Arrays.asList(functionData));
            if (needAddMore) {
                list.add("更多");
            }
            return list;
        } else {
            ArrayList<String> list = new ArrayList<>(Arrays.asList(functionData));
            list.add(9, "更多");
            return new ArrayList<>(list.subList(0, 10));
        }
    }


    /**
     * 模拟统计面板数据获取
     */
    private ArrayList<String> getStatisticsData() {
        StatisticsBean data = GsonUtils.getGson().fromJson(UserInfoMgr.statisticsData, StatisticsBean.class);
        HiLog.debug(label, "data = " + data);
        statisticNames.clear();
        if (data == null) {
            return new ArrayList<>();
        }
        if (data.getNames() != null) {
            statisticNames.addAll(data.getNames());
        }
        if (data.getUrls() != null) {
            HiLog.debug(label, "data.size = " + data.getUrls().size());
            return data.getUrls();
        } else {
            return new ArrayList<>();
        }
    }


    private void initBanner() {
        ArrayList<Integer> dummyImages = new ArrayList<>();
        dummyImages.add(ResourceTable.Media_bg_banner);
        dummyImages.add(ResourceTable.Media_bg_banner);
        DirectionalLayout bannerContainer = findComponentById(ResourceTable.Id_bannerContainer);
        Banner banner = null;
        DirectionalLayout.LayoutConfig layoutConfig = new DirectionalLayout.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);
        try {
            banner = new Banner(this);
            banner.setLayoutConfig(layoutConfig);
            banner.setImageLoader(new GlideImageLoader());
            banner.setImages(dummyImages);
            banner.setScaleType(Image.ScaleMode.ZOOM_CENTER.ordinal());
            banner.setDelayTime(5000);
            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            banner.start();
            bannerContainer.addComponent(banner);
        } catch (Exception e) {
            e.printStackTrace();
            bannerContainer.setVisibility(Component.HIDE);
        }
    }

    private void setListContainerHeight(ListContainer listContainer) {
        // 获取当前listContainer的适配器
        BaseItemProvider BaseItemProvider = listContainer.getItemProvider();
        if (BaseItemProvider == null) {
            return;
        }
        int itemHeight = 0;
        for (int i = 0; i < BaseItemProvider.getCount(); i++) {
            // 循环将listContainer适配器的Item数据进行累加
            Component listItem = BaseItemProvider.getComponent(i, null, listContainer);
            // itemHeight += listItem.getHeight();
            itemHeight += SizeUtils.vp2px(173);
        }
        // 对当前listContainer进行高度赋值
        ComponentContainer.LayoutConfig config = listContainer.getLayoutConfig();
        // 这边加上(listContainer.getBoundaryThickness() * (BaseItemProvider.getCount()+1))
        // listContainer.getBoundaryThickness() 就是分界线的高度
        //(BaseItemProvider.getCount()+1) 是Item的数量  加1  是因为顶部还有一条分界线
        config.height = itemHeight
                + (listContainer.getBoundaryThickness() * (BaseItemProvider.getCount() + 1));
        // 赋值
        listContainer.setLayoutConfig(config);
    }
}
